package book;

import constant.Constant;
import util.AnalyzingBook;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

public class Library {
    private Book[] books;//当前图书数组；
    private int countBook;//实际存储书籍个数；
     private AnalyzingBook analyzingBook=new AnalyzingBook();
     private  static Library library;//单例化模式；
     private Scanner scanner=new Scanner(System.in);
    private  Library(){
        //构造函数；
        loadAllBook();
    }

    public int getCountBook() {
        return countBook;
    }

    public void setCountBook(int countBook) {
        this.countBook = countBook;
    }

    //单例模式之懒汉模式；
    public  static Library getLibrary(){
        if(library==null){
            library=new Library();
        }
        return library;
    }
    private void loadAllBook(){
            Book[] allBook=analyzingBook.loadObject(Constant.ALL_BOOK_FILE_NAME);
            books=new Book[Constant.CAPACITY];
            if(allBook==null){
                countBook=0;
            } else if (allBook.length>books.length) {
                books=new Book[allBook.length];
            }
            for(int i=0;i< allBook.length;i++){
                books[i]=allBook[i];
            }
            countBook=allBook.length;
    }
    private void storeBook(){
        analyzingBook.storeObject(books,Constant.ALL_BOOK_FILE_NAME);
    }


    public void displayBook() {
        System.out.println("显示书籍");
        loadAllBook();
        for(int i=0;i<getCountBook();i++){
            System.out.println(books[i]);
        }
    }

    public void exit() {
        System.out.println("退出系统");
        System.exit(0);
    }

    public void addBook(Book book) {
        System.out.println("上架书籍...");
        if(countBook==books.length){
            System.out.println("图书馆已满，⽆法上架更多图书!");
        }
        //bookId进行自增；
        book.setBookId(countBook++);
        books[countBook++]=book;
        storeBook();//将此书进行存储；
        System.out.println("图书 "+book.getTitle()+"上架成功");
    }
    //寻找书籍ID;
    public Book searchById(int bookId){
        loadAllBook();
        for(int i=0;i<getCountBook();i++){
            Book book=books[i];
            if(book.getBookId()==bookId){
                return book;
            }
        }
        return null;
    }
public void updateBook(Book book){
        //1.进行查找该书所对应的下标；
    int index=searchByIdIndex(book.getBookId());
    //2，添加图书；
    books[index]=book;
    //3.保存书籍到文件中；
    storeBook();
}
private int searchByIdIndex(int bookId){
        loadAllBook();
        for(int i=0;i<getCountBook();i++){
            Book book=books[i];
            if(book.getBookId()==bookId){
                return i;
            }
        }
        return -1;
   }
   public void removeBook(int bookId){
        loadAllBook();
        int index=searchByIdReturnIndex(bookId);
        if(index==-1){
            System.out.println("没有你想要删除的图书");
            return;
        }
        int i=index;
        for(;i<countBook-1;i++){
            books[i]=books[i+1];
        }
        books[countBook-1]=null;
        countBook--;
        storeBook();

   }
   private int searchByIdReturnIndex(int bookId){
        loadAllBook();
        for(int i=0;i<getCountBook();i++){
            Book book=books[i];
            if(book.getBookId()==bookId){
                return i;
            }
        }
        return -1;
   }
   public void borrowCount(){
        loadAllBook();
        for(int i=0;i<countBook;i++){
            Book book=books[i];
            System.out.println("图书"+book.getTitle()+"借阅次数"+book.getBorrowCount());
        }
   }
   public void generateBook(int k) {
       //1.定义一个替代数组进行存储文件中的书籍
       // 2.将替代数组进行关于ID排序
       // 3，将替代数组中前k个元素进行存入新的数组
       // 4，将新的数组进行遍历输出；
       loadAllBook();
       Book[] tmp = new Book[getCountBook()];
       for (int i = 0; i < getCountBook(); i++) {
           tmp[i] = books[i];
       }
       Book[] generateBooks = new Book[k];
       Arrays.sort(tmp);
       for (int i = 0; i < k; i++) {
           generateBooks[i] = tmp[i];
       }
       System.out.println("最受欢迎的前K本书如下：");
       for (int i = 0; i < k; i++) {
           Book book = generateBooks[i];
           System.out.println("书名：" + book.getTitle() + " 作者：" +
                   book.getTitle() + " 借阅次数：" + book.getBorrowCount());


       }
   }
   public void checkInventoryStatus(){
        System.out.println("-----------------------");
        for(int i=0;i<countBook;i++){
            Book book=books[i];
            String sta=book.isBorrowed() ? "以借出":"在管";
            System.out.println("书名"+book.getTitle()+"目前状态"+sta);
        }
        System.out.println("---------------------------");

   }
   public void checkAndRemoveOldBooks(){
        //方法
       // 1.获取当前时间戳；
       // 2将当前时间转换成localdate类型
       // 3.获取当前书籍的上架时间
       // 4，计算当前时间与上架时间差值
       // 5，如果时间差值超过一年进行删除：

           loadAllBook();
           // 获取当前时间戳
           long currentTimestamp = System.currentTimeMillis();

           // 将当前时间戳转换为 LocalDate
           LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp)
                   .atZone(ZoneId.systemDefault())
                   .toLocalDate();

           boolean flg = false;
           for (int i = 0; i < getCountBook(); i++) {
               Book book = books[i];
               //获取当前书籍的上架时间
               LocalDate specifiedDate = book.getShelfDate();

               // 计算两个日期之间的差值（以年为单位）
               long yearsBetween = ChronoUnit.YEARS.between(specifiedDate, currentDate);

               if(yearsBetween >= 1) {
                   System.out.print("图书 " + book.getTitle() + " 已经上架超过一年，是否移除？ (y/n)：");
                   String response = scanner.nextLine();
                   if (response.equalsIgnoreCase("y")) {
                       //确认删除调用remove方法进行删除
                       removeBook(book.getBookId());
                       i--;  // 因为后面的书已经向前移动，所以要重新检查当前索引位置
                   }
                   flg = true;
               }
           }
           if(!flg) {
               System.out.println("没有上架超过一年的图书！");
           }
           storeBook();
       }
       public void borrowBook(int bookId){
        loadAllBook();
        for(int i=0;i<countBook;i++){
            Book book=books[i];
            if(book.getBookId()==bookId){
                book.setBorrowed(true);
                book.incrementBorrowCount();
            }
        }
        storeBook();
       }
       public void returnBook(int bookId){
        loadAllBook();
        for(int i=0;i<countBook;i++){
            Book book=books[i];
            if(book.getBookId()==bookId){
                book.setBorrowed(false);
                book.decreaseBorrowCount();
            }
        }
        storeBook();
       }
    public void searchBook() {
        System.out.println("请输入你要查找的图书的名称：");
        String title = scanner.nextLine();

        Book book = searchBookByTitle(title);
        if(book == null) {
            System.out.println("没有你要查找的这本书！");
            return;
        }

        System.out.println("找到了你要查找的书，书的详细信息如下：");
        System.out.println(book);
    }

    public Book searchBookByTitle(String title) {
        for (int i = 0; i < countBook; i++) {
            Book book = books[i];
            if(book.getTitle().equals(title)) {
                return book;
            }
        }
        return null;
    }


}


